package com.vxfly.helioscamera.Activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.vxfly.helioscamera.R;
import com.vxfly.helioscamera.SDKAPI.CameraProperties;
import com.vxfly.helioscamera.adapter.LHPWifiListAdapter;
import com.vxfly.helioscamera.adapter.WifiListAdapter;
import com.vxfly.helioscamera.baseItems.WifiSsidPwd;
import com.vxfly.helioscamera.camera.MyCamera;
import com.vxfly.helioscamera.function.ActivityCollector;
import com.vxfly.helioscamera.function.SystemCheckTools;
import com.vxfly.helioscamera.function.WifiCheck;
import com.vxfly.helioscamera.function.WifiHistory;
import com.vxfly.helioscamera.global.App.ExitApp;
import com.vxfly.helioscamera.global.App.GlobalInfo;
import com.vxfly.helioscamera.global.App.PropertyId;
import com.vxfly.helioscamera.log.WriteLogToDevice;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by kaifa on 2016/12/29.
 */
public class LHPWifiConnectActivity extends Activity {
    private final static String TAG="LHPWifiConnectActivity";

    private ListView wifiListView;
    private List<ScanResult> wifiList;
    private WifiCheck wifiCheck;
    private LHPWifiListAdapter wifiListAdapter;
    private int reconnectTime;
    private ScanResult currentChooseWifi;
    public static final int CONNECT_WIFI_SUCCESS = 0;
    public static final int CONNECT_WIFI_FAIL = 1;
    public static final int CONNECT_DEVICE_SUCCESS = 2;
    public static final int CONNECT_DEVICE_FAIL = 3;
    public static final int REFRESH_TIME_OUT = 4;
    private ProgressDialog progressDialog;
    private MyHandler myHandler;
    private Timer timer;
    private MyCamera currentCamera;

    //
//    private class ItemData{
//        int currentItemIndex;
//        int S
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wifi_connect_lhp);

        wifiCheck = new WifiCheck();
        myHandler = new MyHandler();

        WifiManager mWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = mWifi.getConnectionInfo();


        wifiListView = (ListView) findViewById(R.id.choose_wifi_list_scan);
        //JIRA ICOM-1991 ICOM-1992 Begin Add by b.jiang 2015-09-21
        wifiList = wifiCheck.getWifiListWithStartString();
        //JIRA ICOM-1991 ICOM-1992 End Add by b.jiang 2015-09-21
        wifiListAdapter = new LHPWifiListAdapter(LHPWifiConnectActivity.this, wifiList);
        wifiListView.setAdapter(wifiListAdapter);

        ActivityCollector.addActivity(this);
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_2://return，返回
                //ActivityCollector.finishAll();
                finish();
                break;
            case KeyEvent.KEYCODE_1://搜索
                refreshWifiList();
                break;
            case KeyEvent.KEYCODE_6://进行连接
                connectWifi();
                break;
            case KeyEvent.KEYCODE_7://down
                wifiListAdapter.nextItemSelected();
                break;
            case KeyEvent.KEYCODE_3://up
                wifiListAdapter.preItemSelected();
                break;
            default:
                return super.onKeyDown(keyCode, event);
        }

        return true;
    }


    public void refreshWifiList(){
        if (progressDialog != null) {
                progressDialog.dismiss();
        }
        showProgressDialog(LHPWifiConnectActivity.this.getString(R.string.dialog_refreshing));
        timer = new Timer(true);
        TimerTask refreshTask = new TimerTask() {
                @Override
                public void run() {

                    WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "appstart run:");
                    myHandler.obtainMessage(REFRESH_TIME_OUT).sendToTarget();

                }
            };
        timer.schedule(refreshTask, 5000);
    }

    public void connectWifi(){
        showProgressDialog(LHPWifiConnectActivity.this.getString(R.string.dialog_init_network));
        currentChooseWifi= wifiListAdapter.getCurrentItemScanResult();
        wifiCheck.connectWifi(currentChooseWifi.SSID, "1234567890", wifiCheck.getSecurity(currentChooseWifi));
        reconnectTime = 0;
        final Timer connectTimer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if (wifiCheck.isWifiConnected(LHPWifiConnectActivity.this, currentChooseWifi.SSID) == true) {
                    WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "isWifiConnect() == true");
                    if (connectTimer != null) {
                        connectTimer.cancel();
                    }
                    myHandler.obtainMessage(CONNECT_WIFI_SUCCESS).sendToTarget();
                    return;
                } else {
                    WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "isWifiConnect() == false  reconnectTime ="
                            + reconnectTime);
                    reconnectTime++;
                    if (reconnectTime >= 20) {
                        if (connectTimer != null) {
                            connectTimer.cancel();
                        }
                        myHandler.obtainMessage(CONNECT_WIFI_FAIL).sendToTarget();
                        return;
                    }
                }
            }
        };
        connectTimer.schedule(task, 0, 3000);
    }

    private class MyHandler extends Handler {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CONNECT_WIFI_SUCCESS:
                    WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "CONNECT_SUCCESS");
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    showProgressDialog(LHPWifiConnectActivity.this.getString(R.string.dialog_connecting_to_cam));
                    initAPP(currentChooseWifi.SSID);
                    break;
                case CONNECT_WIFI_FAIL:
                    WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "CONNECT_FAIL");
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    Toast.makeText(LHPWifiConnectActivity.this, R.string.dialog_connect_failed, Toast.LENGTH_LONG).show();
                    break;
                case CONNECT_DEVICE_SUCCESS:
                    WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "CONNECT_SUCCESS");
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    Intent intent = new Intent(LHPWifiConnectActivity.this, Main.class);
                    startActivity(intent);
                    break;
                case CONNECT_DEVICE_FAIL:
                    WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "CONNECT_FAIL");
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    Toast.makeText(LHPWifiConnectActivity.this, R.string.dialog_connect_failed, Toast.LENGTH_LONG).show();
                    break;
                case REFRESH_TIME_OUT:
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    wifiListAdapter.notifyDataSetChanged();
                    //wifiList = wifiCheck.getWifiList();
                    //JIRA ICOM-1991 ICOM-1992 Begin Add by b.jiang 2015-09-21
                    wifiList = wifiCheck.getWifiListWithStartString();
                    //JIRA ICOM-1991 ICOM-1992 Begin Add by b.jiang 2015-09-21
                    wifiListAdapter = new LHPWifiListAdapter(LHPWifiConnectActivity.this, wifiList);
                    wifiListView.setAdapter(wifiListAdapter);
                    break;
            }

        }
    }

    private void showProgressDialog(String message) {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        progressDialog = new ProgressDialog(LHPWifiConnectActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(message);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    private void initAPP(String ssid) {
        WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "isWifiConnect() == true");
        currentCamera = new MyCamera();
        if (currentCamera.getSDKsession().prepareSession() == false) {
            // redirectToExit();
            myHandler.obtainMessage(CONNECT_DEVICE_FAIL).sendToTarget();
            return;
        }
        if (currentCamera.getSDKsession().checkWifiConnection() == true) {
            GlobalInfo.getInstance().addCamera(currentCamera);
            GlobalInfo.getInstance().setCurrentCamera(currentCamera);
            currentCamera.initCamera();
            if (CameraProperties.getInstance().hasFuction(PropertyId.CAMERA_DATE)) {
                long time = System.currentTimeMillis();
                Date date = new Date(time);
                SimpleDateFormat myFmt = new SimpleDateFormat("yyyyMMdd HHmmss");
                String temp = myFmt.format(date);
                temp = temp.replaceAll(" ", "T");
                temp = temp + ".0";
                CameraProperties.getInstance().setCameraDate(temp);
            }
//			CameraInfoHistory.save(new CameraStoreInfo(CameraProperties.getInstance().getCameraName(), currentCamera.getSDKsession()
//					.getUId(), CameraProperties.getInstance().getCameraPasswordNew()), WifiConnectActivity.this);
            currentCamera.setMyMode(1);
            myHandler.obtainMessage(CONNECT_DEVICE_SUCCESS).sendToTarget();
            return;
        } else {
            WriteLogToDevice.writeLog("[ERROR] -- AppStartActivity: ", "..........checkWifiConnection  fail");
            myHandler.obtainMessage(CONNECT_DEVICE_FAIL).sendToTarget();
            return;
        }
    }

    private void showDialog(String message) {
//        AlertDialog.Builder builder = new AlertDialog.Builder(LHPWifiConnectActivity.this);
//        builder.setMessage(message);
//        builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
//
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//            }
//        });
//        AlertDialog dialog = builder.create();
//        dialog.setCancelable(false);
//        dialog.show();
    }


}
